package com.bw.controller;

import com.alibaba.fastjson.JSON;
import com.bw.entity.User;
import com.bw.mapper.UserMapper;
import org.spring.kun.common.Md5Utils;
import org.spring.kun.common.TokenUtils;
import org.spring.kun.common.ZzyUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.concurrent.TimeUnit;

@Controller
public class LoginController {

    @Autowired
    UserMapper userMapper;

    @Autowired
    RedisTemplate redisTemplate;

    @RequestMapping("/loginPage.do")
    public String loginPage(){
            // hello world
        return "login";
    }


    @RequestMapping("/login.do")
    public String login(@Valid User loginUser, BindingResult result, Model model, HttpServletRequest request, HttpServletResponse response){

        if (result.hasErrors()){

            model.addAttribute("error",result.getAllErrors().get(0).getDefaultMessage());

            return "login";
        }

       User userDB =  userMapper.selectByName(loginUser.getName());
        if (userDB == null){
            model.addAttribute("error","用户名不存在");
            return "login";
        }

        String loginUserPassword = loginUser.getPassword(); //用户输入的密码  123

        String password = userDB.getPassword(); //1396411995a6f76da8124c11bddd18cf
        String salt = userDB.getSalt(); //3dbc2f2e

        String md5String = Md5Utils.getMD5String(loginUserPassword + salt);

        if (!md5String.equals(password)){
            model.addAttribute("error","密码错误");
            return "login";
        }

        //  token令牌  加密用户的信息  得到token令牌   把令牌放入cookie  把cookie返回给用户的浏览器,设置过期时间为30分钟
        TokenUtils.responseTokenByCookie(userDB,response,30);
        // 登录成功之后  把用户信息 存入Redis
        redisTemplate.opsForValue().set(userDB.getName(), JSON.toJSONString(userDB),30, TimeUnit.MINUTES);
        // 发送短信
        ZzyUtils.sendSms("17611221735","登录成功,添加成功,入住成功",5);
        return "redirect:list.do";
    }


    @RequestMapping("/list.do")
    public String list(HttpServletRequest request,Model model){

        User userFromRequest = TokenUtils.getLoginUserFromRequest(request, User.class);

        model.addAttribute("nickName",userFromRequest.getNickName());

        model.addAttribute("avatarUrl",userFromRequest.getAvatarUrl());
        return "list";
    }
}
